<template>
  <div class="detail-shell">
    <div class="detail-container">
      <button class="back-float" @click="goBack">← 返回</button>
      <div v-if="post" class="split-layout">
        <div class="left-media" v-if="images.length > 0">
          <div class="media-bg">
            <img v-if="currentImageUrl" :src="currentImageUrl" alt="背景" />
          </div>
          <div class="media-stage">
            <button class="nav-btn prev" v-if="images.length > 1" @click="prevImage">‹</button>
            <div class="media-frame">
              <img v-if="currentImageUrl" :src="currentImageUrl" alt="展示图" />
            </div>
            <button class="nav-btn next" v-if="images.length > 1" @click="nextImage">›</button>
          </div>
        </div>
        <div class="right-pane" :class="{ 'full-width': images.length === 0 }">
          <div class="pane-header">
            <div class="header-left">
              <div class="avatar">
                <img v-if="post.avatar_url" :src="post.avatar_url" alt="头像" />
                <span v-else>{{ getAvatarText(post.username) }}</span>
              </div>
              <div class="user-meta">
                <div class="nickname">{{ post.username }}</div>
                <div class="sub">{{ formatTime(post.created_at) }}</div>
              </div>
            </div>
            <div class="header-actions">
              
            </div>
          </div>
          <div class="pane-content-fixed">
            <div class="post-content">{{ post.content }}</div>
            <div v-if="post.tags && post.tags.length" class="post-tags">
              <span v-for="tag in post.tags" :key="tag" class="tag" @click="goToTag(tag)">{{ tag }}</span>
            </div>
          </div>
          <div class="pane-scroll">
            <div v-if="comments.length" class="comments-list">
              <div v-for="c in comments" :key="c.comment_id" class="comment-item">
                <div class="comment-header">
                  <div class="comment-author">{{ c.username }}</div>
                  <div class="comment-time">{{ formatTime(c.created_at) }}</div>
                  <button v-if="c.user_id === currentUserId" class="delete-comment-btn" @click="deleteComment(c.comment_id)">🗑️</button>
                </div>
                <div class="comment-content">{{ c.content }}</div>
              </div>
            </div>
            <div v-else class="no-comments">暂无评论，快来抢沙发吧！</div>
          </div>
          <div class="pane-footer">
            <div class="footer-actions">
              <button class="like-btn" :class="{ liked: post.is_liked }" @click="toggleLike(post)"><span class="heart">{{ post.is_liked ? '❤️' : '♡' }}</span><span class="count">{{ post.like_count }}</span></button>
              <button class="icon-btn">↗️</button>
              <button v-if="isCurrentUserPost" class="delete-btn" @click="confirmDelete">🗑️ 删除</button>
            </div>
            <div class="footer-input">
              <input v-model="newComment" class="input" type="text" placeholder="发表评论..." @keydown.enter="submitComment" />
              <button class="send-btn" :disabled="!newComment.trim() || isSubmittingComment" @click="submitComment">发送</button>
            </div>
          </div>
        </div>
      </div>
      <div v-else-if="loading" class="loading-state"><div class="loading-spinner"></div>加载中...</div>
      
      <!-- 错误提示 -->
      <div v-else class="error-state">
        动态不存在或已被删除
        <button class="back-btn" @click="goBack">返回社区</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getPostDetail, likePost, unlikePost, getComments, createComment, deleteComment as deleteCommentApi, deletePost } from '../api/community'
const showMessage = (message: string, type: 'success' | 'error' = 'success') => {
  const toast = document.createElement('div')
  toast.textContent = message
  const base = 'position:fixed;left:50%;bottom:80px;transform:translateX(-50%);padding:10px 16px;border-radius:10px;color:#fff;box-shadow:0 6px 20px rgba(0,0,0,0.25);z-index:9999;font-size:14px;opacity:0.95;'
  const bg = type === 'success' ? 'background:#2E8B57;' : 'background:#E74C3C;'
  toast.setAttribute('style', base + bg)
  document.body.appendChild(toast)
  setTimeout(() => {
    toast.style.transition = 'opacity 0.3s ease'
    toast.style.opacity = '0'
    setTimeout(() => { toast.remove() }, 300)
  }, 1800)
}
const showConfirm = (text: string): Promise<boolean> => {
  return new Promise(resolve => {
    const overlay = document.createElement('div')
    overlay.setAttribute('style', 'position:fixed;inset:0;background:rgba(0,0,0,0.35);z-index:9998')
    const modal = document.createElement('div')
    modal.setAttribute('style', 'position:fixed;left:50%;top:40%;transform:translate(-50%,-50%);min-width:280px;padding:18px 16px;border-radius:12px;background:#222;color:#fff;box-shadow:0 10px 30px rgba(0,0,0,0.3);z-index:9999')
    const msg = document.createElement('div')
    msg.textContent = text
    msg.setAttribute('style', 'font-size:14px;margin-bottom:14px')
    const btns = document.createElement('div')
    btns.setAttribute('style', 'display:flex;gap:10px;justify-content:flex-end')
    const ok = document.createElement('button')
    ok.textContent = '确定'
    ok.setAttribute('style', 'padding:6px 12px;border:none;background:#2E8B57;color:#fff;border-radius:8px;cursor:pointer')
    const cancel = document.createElement('button')
    cancel.textContent = '取消'
    cancel.setAttribute('style', 'padding:6px 12px;border:none;background:#555;color:#fff;border-radius:8px;cursor:pointer')
    ok.onclick = () => { modal.remove(); overlay.remove(); resolve(true) }
    cancel.onclick = () => { modal.remove(); overlay.remove(); resolve(false) }
    btns.appendChild(cancel); btns.appendChild(ok)
    modal.appendChild(msg); modal.appendChild(btns)
    document.body.appendChild(overlay)
    document.body.appendChild(modal)
  })
}

const router = useRouter()
const route = useRoute()

// 响应式数据
const post = ref<any>(null)
const loading = ref(true)
const showComments = ref(true) // 默认显示评论
const comments = ref<any[]>([])
const newComment = ref('')
const triggerPointsToast = inject<(delta: number) => void>('triggerPointsToast')
const isFollowing = ref(false)
const images = computed<string[]>(() => {
  const arr = post.value?.image_urls || []
  return Array.isArray(arr) ? arr : []
})
const currentIndex = ref(0)
const currentImageUrl = computed(() => images.value[currentIndex.value] || '')

// 计算属性
const isCurrentUserPost = computed(() => {
  const currentUserId = localStorage.getItem('user_id')
  return post.value?.user_id === currentUserId
})

const currentUserId = computed(() => {
  return localStorage.getItem('user_id')
})

// 方法
const loadPostDetail = async () => {
  loading.value = true
  try {
    const postId = route.params.id
    const response: any = await getPostDetail(Number(postId as any))
    if (response && response.data) {
      post.value = response.data
      loadComments(Number(postId as any))
    } else {
      showMessage('获取动态详情失败', 'error')
    }
  } catch (error) {
    console.error('获取动态详情错误:', error)
    showMessage('加载失败，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

const loadComments = async (postId: string | number) => {
  try {
    const response: any = await getComments(Number(postId as any))
    if (response && response.data) {
      comments.value = response.data.comments || []
    }
  } catch (error) {
    console.error('获取评论错误:', error)
  }
}

const toggleLike = async (postData: any) => {
  try {
    const originalLiked = postData.is_liked
    const originalCount = postData.like_count
    
    // 先更新UI
    if (postData.is_liked) {
      postData.like_count--
      postData.is_liked = false
    } else {
      postData.like_count++
      postData.is_liked = true
    }
    
    // 调用接口
    if (originalLiked) {
      await unlikePost(postData.post_id)
      showMessage('取消点赞成功')
    } else {
      await likePost(postData.post_id)
      showMessage('点赞成功')
      triggerPointsToast?.(1)
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    // 恢复原始状态
    post.value.is_liked = !post.value.is_liked
    post.value.like_count = post.value.is_liked ? post.value.like_count + 1 : post.value.like_count - 1
    showMessage('操作失败，请稍后重试', 'error')
  }
}

// 添加评论提交状态
const isSubmittingComment = ref(false)

const submitComment = async () => {
  if (!newComment.value.trim()) return
  
  // 添加加载状态
  const originalContent = newComment.value
  isSubmittingComment.value = true
  
  try {
    const commentData = {
      content: newComment.value.trim()
    }
    
    const response = await createComment(post.value.post_id, commentData)
    // 检查响应是否成功（兼容不同的响应格式）
    if (response && response.data) {
      comments.value.unshift(response.data)
      post.value.comment_count++
      newComment.value = ''
      showMessage('评论成功')
      triggerPointsToast?.(2)
    } else {
      showMessage('评论失败，服务器返回异常', 'error')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    showMessage('评论失败，请稍后重试', 'error')
    // 恢复输入框内容
    newComment.value = originalContent
  } finally {
    isSubmittingComment.value = false
  }
}

const deleteComment = async (commentId: number) => {
  try {
    await deleteCommentApi(commentId)
    comments.value = comments.value.filter(c => c.comment_id !== commentId)
    post.value.comment_count--
    showMessage('删除评论成功')
  } catch (error) {
    console.error('删除评论失败:', error)
    showMessage('删除失败，请稍后重试', 'error')
  }
}

const confirmDelete = async () => {
  const ok = await showConfirm('确定要删除这条动态吗？')
  if (!ok) return
  try {
    await deletePost(post.value.post_id)
    showMessage('删除动态成功')
    router.push('/community')
  } catch (error) {
    console.error('删除动态失败:', error)
    showMessage('删除失败，请稍后重试', 'error')
  }
}

const goBack = () => {
  router.back()
}

const goToTag = (tagName: string) => {
  router.push({ path: '/community', query: { tag: tagName } })
}

const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getAvatarText = (username: string) => {
  return username ? username.charAt(0).toUpperCase() : '?'
}

// 生命周期
onMounted(() => {
  loadPostDetail()
})
watch(post, () => { currentIndex.value = 0 })
const prevImage = () => {
  if (!images.value.length) return
  currentIndex.value = (currentIndex.value - 1 + images.value.length) % images.value.length
}
const nextImage = () => {
  if (!images.value.length) return
  currentIndex.value = (currentIndex.value + 1) % images.value.length
}
const toggleFollow = () => { isFollowing.value = !isFollowing.value }
</script>

<style scoped>
.detail-shell { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: #f5f5f5; }
.detail-container { position: relative; width: 100%; max-width: 1200px; height: 85vh; background: #fff; border-radius: 16px; overflow: hidden; display: flex; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); }
.split-layout { display: contents; }
.left-media { position: relative; width: 60%; display: flex; align-items: center; justify-content: center; background: #f0f2f5; overflow: hidden; }
.media-bg { position: absolute; inset: 0; overflow: hidden; z-index: 0; opacity: 0.5; }
.media-bg img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; filter: blur(60px) saturate(1.5); transform: scale(1.2); }
.media-stage { position: relative; z-index: 10; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; padding: 40px; box-sizing: border-box; }
.media-frame { max-width: 100%; max-height: 100%; display: flex; align-items: center; justify-content: center; transition: transform 0.3s ease; }
.media-frame img { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; box-shadow: 0 20px 40px rgba(0,0,0,0.2); border-radius: 8px; }
.nav-btn { position: absolute; top: 50%; transform: translateY(-50%); width: 48px; height: 48px; border: none; border-radius: 50%; background: rgba(255,255,255,0.8); color: #333; cursor: pointer; z-index: 11; font-size: 24px; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.nav-btn:hover { background: #fff; transform: translateY(-50%) scale(1.1); box-shadow: 0 6px 16px rgba(0,0,0,0.15); }
.nav-btn.prev { left: 24px; }
.nav-btn.next { right: 24px; }
.right-pane { width: 40%; background: rgba(255,255,255,0.95); display: flex; flex-direction: column; position: relative; z-index: 2; backdrop-filter: blur(10px); }
.right-pane.full-width { width: 100%; max-width: 800px; margin: 0 auto; border-radius: 16px; }
.pane-header { height: 64px; display: flex; align-items: center; justify-content: space-between; padding: 0 20px; background: #fff; border-bottom: 1px solid rgba(0,0,0,0.03); }
.header-left { display: flex; align-items: center; gap: 12px; }
.back-float { position: absolute; top: 20px; left: 20px; z-index: 100; border: 1px solid rgba(255,255,255,0.2); background: rgba(0,0,0,0.4); backdrop-filter: blur(8px); color: #fff; padding: 8px 14px; border-radius: 20px; cursor: pointer; transition: all 0.2s ease; font-weight: 500; font-size: 14px; display: flex; align-items: center; gap: 4px; }
.back-float:hover { background: rgba(0,0,0,0.6); transform: translateX(-2px); }
@media (max-width: 768px) { .back-float { top: 12px; left: 12px; background: rgba(0,0,0,0.6); } }
.avatar { width: 42px; height: 42px; border-radius: 50%; overflow: hidden; background: #f0f2f5; color: #666; display: flex; align-items: center; justify-content: center; font-weight: 600; border: 1px solid rgba(0,0,0,0.05); }
.avatar img { width: 100%; height: 100%; object-fit: cover; }
.user-meta .nickname { font-size: 15px; font-weight: 600; color: #1a1a1a; margin-bottom: 2px; }
.user-meta .sub { font-size: 12px; color: #999; }
.header-actions { display: flex; align-items: center; gap: 8px; }
.pane-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}
.pane-content-fixed { flex: 0 0 auto; padding: 20px 20px 10px; }
.pane-scroll::-webkit-scrollbar { width: 5px; }
.pane-scroll::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 999px; }
.pane-scroll { scrollbar-width: thin; }
.post-content { color: #333; line-height: 1.7; margin-bottom: 12px; white-space: pre-wrap; word-break: break-word; font-size: 15px; }
.post-tags { margin: 8px 0 16px; display: flex; flex-wrap: wrap; gap: 8px; }
.tag { display: inline-block; padding: 4px 10px; margin: 0; background-color: #f5f7fa; color: #666; border-radius: 6px; cursor: pointer; font-size: 12px; transition: all 0.2s; }
.tag:hover { background: #e0e4e8; color: #333; }
.comments-list { display: flex; flex-direction: column; padding: 0 20px 20px; }
.comment-item { padding: 16px 0; border-bottom: 1px solid #f8f8f8; }
.comment-item:last-child { border-bottom: none; }
.comment-header { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.comment-author { font-size: 14px; font-weight: 600; color: #333; }
.comment-time { margin-left: auto; font-size: 12px; color: #ccc; }
.delete-comment-btn { padding: 4px; background: transparent; color: #ccc; border: none; cursor: pointer; font-size: 14px; transition: color 0.2s; }
.delete-comment-btn:hover { color: #ff6b6b; }
.comment-content { font-size: 14px; color: #444; line-height: 1.6; padding-left: 0; }
.no-comments { text-align: center; color: #999; padding: 40px 0; font-size: 14px; }
.pane-footer { padding: 12px 20px; border-top: 1px solid #f8f8f8; background: #fff; }
.footer-actions { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
.icon-btn { padding: 6px 10px; border-radius: 10px; background: #f8f9fa; border: 1px solid #eee; cursor: pointer; color: #6c757d; }
.like-btn { display: inline-flex; align-items: center; gap: 6px; padding: 0; border: none; background: transparent; cursor: pointer; }
.like-btn .heart { font-size: 18px; color: #9aa0a6; transition: transform 0.15s ease, filter 0.2s ease; }
.like-btn .count { color: #6c757d; transition: color 0.2s ease; }
.like-btn:hover .heart { color: #e74c3c; }
.like-btn.liked .heart { color: inherit; transform: scale(1.06); filter: drop-shadow(0 2px 6px rgba(231,76,60,0.25)); }
.like-btn.liked .count { color: #FF7A00; }
.icon-btn .count { margin-left: 6px; }
.footer-input { display: flex; gap: 8px; }
.input { flex: 1; height: 38px; border-radius: 999px; border: 1px solid #ddd; padding: 0 14px; }
.send-btn { padding: 0 16px; border: none; border-radius: 999px; background: #42b983; color: #fff; cursor: pointer; }
.send-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.loading-state, .error-state { display: flex; align-items: center; justify-content: center; color: #6c757d; }
.loading-spinner { width: 32px; height: 32px; border: 3px solid #f3f3f3; border-top: 3px solid #42b983; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 8px; }
@keyframes spin { 0% { transform: rotate(0deg) } 100% { transform: rotate(360deg) } }
@media (max-width: 768px) { .detail-container { height: auto; flex-direction: column; border-radius: 0; box-shadow: none; } .left-media, .right-pane { width: 100%; } .left-media { min-height: 50vh; } }
</style>
